iT邦幫忙

2025 iThome 鐵人賽

DAY 30
0

Assertion

斷言(Assertion)用於驗證某個內容是否符合應該遵循的方法
在 js 中,斷言可由一個expression(which return true/false)throw new Error 構成,當遭遇意外情況或條件為假時,會立即拋出例外(throw exception)並停止程式碼執行,換句話說就是確保表達式條件為真的檢查

以下為 assertion 與 console.assert() 的示例

function assert(condition, message) {
    if (!condition) {
        throw new Error(message);
    }
    console.log("The code won't reach here if assertion is not passed");
}

function isEven(num) {
    return num % 2 === 0 ? true : false;
}

try {
    assert(isEven(3), "not a even number");
} catch (e) {
    console.log(e);
}

console.assert

console.assert(assertion , errorMessage)
『斷言為假』 時,會將錯誤訊息寫入 console,若斷言為真則不作用
console.assert 並 『不會阻止程式運行』,僅將錯誤寫入log,所以如果要確保程式停止作用,仍須仰賴throw exception的作用

另外 console.error(message) 也會將錯誤訊息寫入 console,不過本身為無條件判斷

feature console.assert(assertion , 'errorMessage') console.error('errorMessage')
目的 檢查『是否符合斷言內的條件』,僅在失敗/值為假時輸出訊息 輸出錯誤等級的文字
停止執行(Execution Stop)
斷言特定(Assertion Specific)

參考資料

assert(static)
https://developer.mozilla.org/en-US/docs/Web/API/console/assert_static


上一篇
Chapter 8 Bugs & Errors-day29
系列文
溫故而知新:Eloquent Javascript 閱讀筆記30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言